<?php

namespace app\api\services;

use app\common\controller\Api;
use GuzzleHttp\Client;
use think\Db;

class Config
{

    private $holiday = ['2022-01-01','2022-01-02','2022-01-03','2022-01-31','2022-02-01','2022-02-02','2022-02-03','2022-02-04','2022-02-05','2022-02-06','2022-04-03','2022-04-04','2022-04-05','2022-04-06','2022-04-30','2022-05-01','2022-05-02','2022-05-03','2022-05-04','2022-06-03','2022-06-04','2022-06-05','2022-09-10','2022-09-11','2022-09-12','2022-10-01','2022-10-02','2022-10-03','2022-10-04','2022-10-05','2022-10-06','2022-10-07'];//假日列表
    private $weekWork = ['2022-01-29','2022-01-30','2022-04-02','2022-04-24','2022-05-07','2022-10-08','2022-10-09'];//周末需要补班的日期

    private $addAction = [
        ['url'=>'https://news.4399xyxy.com/?from=320104','mode'=>'load'],
        ['url'=>'https://mini.xnnews.com.cn/?from=320104','mode'=>'load']
    ];
    public function getTaskConfig($param=[]){
        $data = [
            'ConfigId'=>'',
            'Url'=>'',
            'Detail'=>'',
            'TimeSpan'=>0,
            'Cookie'=>'',
        ];
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(2);
        if(isset($param['target']) && $param['target']){
            $res = $this->getTaskConfig2($param['target']);
            if($res){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, $param['target']);
                return $res;
            }
            /*$result_target = Db::name('task_config')->find($param['target']);
            if($result_target){
                $data['ConfigId'] = $result_target['Id'];
                $data['Url'] = $result_target['Url'];
                $data['Detail'] = $result_target['Detail'];
                $data['Cookie'] = $result_target['Eigenvalue'];
                $data['TimeSpan'] = $result_target['TimeSpan'];
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, $param['target']);
                return $data;
            }*/
        }
        if($param['type'] == 'dsp'){
            $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 31);
            return $this->getTaskConfig2(31);
        }elseif ($param['type'] == 'create'){
            $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 32);
            return $this->getTaskConfig2(32);
        }elseif ($param['type'] == 'job'){
            $time_yymmdd = date('Y-m-d 00:00:01',time());
            $time_hhiiss = date('H:i:s',time());
            $job_arr = Db::name('task_config')->alias('c')
                ->field('c.Id')
                ->join('params_type p','c.params_type_id = p.id','left')
                ->where('p.status','=',1)
                ->where('p.name','=','job')
                ->where('c.Status','=',1)
                ->column('c.Id');
            if(!$job_arr){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 34);
                return $this->getTaskConfig2(34);
            }

            $job_str = implode(',',$job_arr);
            $sql1 = "SELECT * FROM `fa_task_config` WHERE Id in (".$job_str.") and  TIME_TO_SEC(`DateStart`) <= TIME_TO_SEC('".$time_yymmdd."')  AND TIME_TO_SEC(`DateEnd`) > TIME_TO_SEC('".$time_yymmdd."')  AND `TimeStart` <= '".$time_hhiiss."'  AND `TimeEnd` > '".$time_hhiiss."';";
            $result = Db::query($sql1);
            if(!$result){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 34);
                return $this->getTaskConfig2(34);
            }

            //TODO 先随机取任务ID然后判断是不是已经超出限制 如果超出限制则返回默认 34 的配置
            $ps = [];
            foreach ($result as $item){
                $ps[$item['Id']] = $item['Count'];
            }
            $configId = $this->random($ps);

            if((int)$redis->zScore('task_config_'.date('Y-m-d'),$configId)){
                $actual_count_redis = (int)$redis->zScore('task_config_'.date('Y-m-d'),$configId);
            }else{
                $actual_count_redis = 0;
            }
            //TODO 判断当日是否是节假日
            $day = date('Y-m-d',time());
            $w = date('w',time());
            $rate = 1;
            if(in_array($day,$this->holiday) || (($w === '6' || $w === '0' ) && !in_array($day,$this->weekWork))){//是节假日 或 则判断数量为 原来数量的 70%
                $rate = 0.7;
            }
            if($actual_count_redis >= $ps[$configId]*1.15 * $rate){
                $configId = 34;
            }
            $redis->zIncrBy('task_config_'.date('Y-m-d'),1, $configId);
            return $this->getTaskConfig2($configId,'job');
        }elseif ($param['type'] == 'kuaipai'){
            $params = Db::name('params_type')->where('status','=',1)->where('name','=','kuaipai')->find();
            if(empty($params)){
               return false;
            }
            $redis = new \Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->select(2);
            $time_yymmdd = date('Y-m-d 00:00:01',time());
            $time_hhiiss = date('H:i:s',time());

            $sql1 = "SELECT * FROM `fa_task_config` WHERE params_type_id=".$params['id']." and `Count`>0 and TIME_TO_SEC(`DateStart`) <= TIME_TO_SEC('".$time_yymmdd."')  AND TIME_TO_SEC(`DateEnd`) > TIME_TO_SEC('".$time_yymmdd."')  AND `TimeStart` <= '".$time_hhiiss."'  AND `TimeEnd` > '".$time_hhiiss."';";
            $result = Db::query($sql1);
            if(!empty($result)){
                $ps = [];
                foreach ($result as $item){
                    $ps[$item['Id']] = $item['Count'];
                }
                $configId = $this->random($ps);

                if((int)$redis->zScore('task_config_'.date('Y-m-d'),$configId)){
                    $actual_count_redis = (int)$redis->zScore('task_config_'.date('Y-m-d'),$configId);
                }else{
                    $actual_count_redis = 0;
                }

                if($actual_count_redis >= $ps[$configId]){
                    return false;
                }
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, $configId);
                return $this->getTaskConfig2($configId);

            }else{
                return false;
            }
        }elseif ($param['type'] == 'dongfang'){
            $time_yymmdd = date('Y-m-d 00:00:01',time());
            $time_hhiiss = date('H:i:s',time());
            $job_arr = Db::name('task_config')->alias('c')
                ->field('c.Id')
                ->join('params_type p','c.params_type_id = p.id','left')
                ->where('p.status','=',1)
                ->where('p.name','=','dongfang')
                ->where('c.Status','=',1)
                ->column('c.Id');
            if(!$job_arr){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 34);
                return $this->getTaskConfig2(34);
            }

            $job_str = implode(',',$job_arr);
            $sql1 = "SELECT * FROM `fa_task_config` WHERE Id in (".$job_str.") and  TIME_TO_SEC(`DateStart`) <= TIME_TO_SEC('".$time_yymmdd."')  AND TIME_TO_SEC(`DateEnd`) > TIME_TO_SEC('".$time_yymmdd."')  AND `TimeStart` <= '".$time_hhiiss."'  AND `TimeEnd` > '".$time_hhiiss."';";
            $result = Db::query($sql1);
            if(!$result){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 34);
                return $this->getTaskConfig2(34);
            }

            //TODO 先随机取任务ID然后判断是不是已经超出限制 如果超出限制则返回默认 34 的配置
            $ps = [];
            foreach ($result as $item){
                $ps[$item['Id']] = $item['Count'];
            }
            $configId = $this->random($ps);

            if((int)$redis->zScore('task_config_'.date('Y-m-d'),$configId)){
                $actual_count_redis = (int)$redis->zScore('task_config_'.date('Y-m-d'),$configId);
            }else{
                $actual_count_redis = 0;
            }
            //TODO 判断当日是否是节假日
            $day = date('Y-m-d',time());
            $w = date('w',time());
            $rate = 1;
            if(in_array($day,$this->holiday) || (($w === '6' || $w === '0' ) && !in_array($day,$this->weekWork))){//是节假日 或 则判断数量为 原来数量的 70%
                $rate = 0.7;
            }
            if($actual_count_redis >= $ps[$configId]*1.15 * $rate){
                $configId = 34;
            }
            $redis->zIncrBy('task_config_'.date('Y-m-d'),1, $configId);
            return $this->getTaskConfig2($configId);
        }elseif ($param['type'] == 'chromium'){//增加测试任务配置获取
            $time_yymmdd = date('Y-m-d 00:00:01',time());
            $time_hhiiss = date('H:i:s',time());
            $job_arr = Db::name('task_config')->alias('c')
                ->field('c.Id')
                ->join('params_type p','c.params_type_id = p.id','left')
                ->where('p.status','=',1)
                ->where('p.name','=','chromium')
                ->where('c.Status','=',1)
                ->column('c.Id');
            if(!$job_arr){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 410);
                return $this->getTaskConfig2(410);
            }

            $job_str = implode(',',$job_arr);
            $sql1 = "SELECT * FROM `fa_task_config` WHERE Id in (".$job_str.") and  TIME_TO_SEC(`DateStart`) <= TIME_TO_SEC('".$time_yymmdd."')  AND TIME_TO_SEC(`DateEnd`) > TIME_TO_SEC('".$time_yymmdd."')  AND `TimeStart` <= '".$time_hhiiss."'  AND `TimeEnd` > '".$time_hhiiss."';";
            $result = Db::query($sql1);
            if(!$result){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 410);
                return $this->getTaskConfig2(410);
            }

            //TODO 先随机取任务ID然后判断是不是已经超出限制 如果超出限制则返回默认 34 的配置
            $ps = [];
            foreach ($result as $item){
                $ps[$item['Id']] = $item['Count'];
            }
            $configId = $this->random($ps);

            if((int)$redis->zScore('task_config_'.date('Y-m-d'),$configId)){
                $actual_count_redis = (int)$redis->zScore('task_config_'.date('Y-m-d'),$configId);
            }else{
                $actual_count_redis = 0;
            }
            //TODO 判断当日是否是节假日
            $day = date('Y-m-d',time());
            $w = date('w',time());
            $rate = 1;
            if(in_array($day,$this->holiday) || (($w === '6' || $w === '0' ) && !in_array($day,$this->weekWork))){//是节假日 或 则判断数量为 原来数量的 70%
                $rate = 0.7;
            }
            if($actual_count_redis >= $ps[$configId]*1.15 * $rate){
                $configId = 410;
            }
            $redis->zIncrBy('task_config_'.date('Y-m-d'),1, $configId);
            return $this->getTaskConfig2($configId);
        }elseif($param['type']=='baoguang'){
            $time_yymmdd = date('Y-m-d 00:00:01',time());
            $time_hhiiss = date('H:i:s',time());
            $job_arr = Db::name('task_config')->alias('c')
                ->field('c.Id')
                ->join('params_type p','c.params_type_id = p.id','left')
                ->where('p.status','=',1)
                ->where('p.name','=','baoguang')
                ->where('c.Status','=',1)
                ->column('c.Id');
            if(!$job_arr){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 412);
                return $this->getTaskConfig2(412);
            }

            $job_str = implode(',',$job_arr);
            $sql1 = "SELECT * FROM `fa_task_config` WHERE Id in (".$job_str.") and  TIME_TO_SEC(`DateStart`) <= TIME_TO_SEC('".$time_yymmdd."')  AND TIME_TO_SEC(`DateEnd`) > TIME_TO_SEC('".$time_yymmdd."')  AND `TimeStart` <= '".$time_hhiiss."'  AND `TimeEnd` > '".$time_hhiiss."';";
            $result = Db::query($sql1);
            if(!$result){
                $redis->zIncrBy('task_config_'.date('Y-m-d'),1, 412);
                return $this->getTaskConfig2(412);
            }

            //TODO 先随机取任务ID然后判断是不是已经超出限制 如果超出限制则返回默认 34 的配置
            $ps = [];
            foreach ($result as $item){
                $ps[$item['Id']] = $item['Count'];
            }
            $configId = $this->random($ps);

            if((int)$redis->zScore('task_config_'.date('Y-m-d'),$configId)){
                $actual_count_redis = (int)$redis->zScore('task_config_'.date('Y-m-d'),$configId);
            }else{
                $actual_count_redis = 0;
            }
            //TODO 判断当日是否是节假日
            $day = date('Y-m-d',time());
            $w = date('w',time());
            $rate = 1;
            if(in_array($day,$this->holiday) || (($w === '6' || $w === '0' ) && !in_array($day,$this->weekWork))){//是节假日 或 则判断数量为 原来数量的 70%
                $rate = 0.7;
            }
            if($actual_count_redis >= $ps[$configId]*1.15 * $rate){
                $configId = 412;
            }
            $redis->zIncrBy('task_config_'.date('Y-m-d'),1, $configId);
            return $this->getTaskConfig2($configId);
        }

        return false;
    }

    private function random($ps){
        static $arr = array();
        $key = md5(serialize($ps));

        if (!isset($arr[$key])) {
            $max = array_sum($ps);
            foreach ($ps as $k=>$v) {
                $v = $v / $max * 10000;
                for ($i=0; $i<$v; $i++) $arr[$key][] = $k;
            }
        }
        return $arr[$key][mt_rand(0,count($arr[$key])-1)];
    }

    public function getTaskConfig2($id,$type = null)
    {
        $data = [
            'ConfigId'=>'',
            'Url'=>'',
            'Detail'=>'',
            'Cookie'=>'',
            'TimeSpan'=>0,
        ];
        $task = Db::name('task_config')->find($id);
        if(!$task){
            return false;
        }

//        if($type && $type == 'job'){
//            $detail = json_decode($task['Detail'],true);
//            $res = Db::name('keywords')->orderRaw('rand()')->limit(1)->select();
//            $keyWord = $res[0]['keywords'];
//            $key_id = $res[0]['id'];
//            $action = $this->generateAction($keyWord);
//            array_push($detail['actions'],$action);
//            /* foreach ($this->addAction as $item) {
//                array_push($detail['actions'],$item);
//            }*/
//            $task['Detail'] = json_encode($detail,JSON_UNESCAPED_UNICODE);
//            Db::name('keyword_record')->insert(['keyword_id'=>$key_id,'create_time'=>time()]);
//        }
        if($id == 412){
            $detail = json_decode($task['Detail'],true);
            foreach ($detail['actions'] as &$item){
                if (isset($item['operations']) && !empty($item['operations'])){
                    foreach ($item['operations'] as $k=>$v){
                        if(isset($v['delay'])){
                            $item['operations'][$k]['delay'] = rand(25,50);
                        }
                    }
                }
            }
            $task['Detail'] = json_encode($detail);
        }
        $data['ConfigId'] = $task['Id'];
        $data['Url'] = $task['Url'];
        $data['Detail'] = $task['Detail'];
        $data['Cookie'] = $task['Eigenvalue'];
        $data['TimeSpan'] = $task['TimeSpan'];
        return $data;

    }

    private function generateAction($keyWord){
        $keyWordArr = [
            "key"=>$keyWord,
            "count"=>1,
            "delay"=>3,
            "script"=>"",
            "operation"=>"paste"
        ];
        $page1 = [
            "count"=> "1",
            "delay"=> 3,
            "script"=> "(function(){ var res = []; var sctop = document.documentElement.scrollTop || document.body.scrollTop; res.push(['scrollTop', sctop]); var item = document.getElementById('su'); var rc = item.getBoundingClientRect(); var href = ''; res.push(['item', rc.left, rc.top, rc.width, rc.height, href]); return res; })();",
            "sub-page"=> [
                "duration"=> 3,
                "operation"=> "browse"
            ],
            "operation"=> "click"
        ];
        $page1Click = [
            "exit"=> false,
            "count"=> "1",
            "delay"=> 10,
            "script"=> "(function () { var res = []; var sctop = document.documentElement.scrollTop || document.body.scrollTop; res.push(['scrollTop', sctop]); var left = document.getElementById('content_left'); if (left) { var items = left.getElementsByClassName('t'); if (items.length > 0) { var index = Math.floor(Math.random() * items.length); var item = items[index]; var targeth = item.getElementsByTagName('a'); if (targeth.length > 0) { var rc = targeth[0].getBoundingClientRect(); var href = targeth[0].href; res.push(['item', rc.left, rc.top, rc.width, rc.height, href]); } } } return res; })();",
            "sub-page"=> [
                "duration"=> 15,
                "operation"=> "browse",
                "needscroll"=> true
            ],
            "operation"=> "click"
        ];
        $operations = [
            [
                "count"=>"1",
                "script"=>"(function(){ var res = []; var sctop = document.documentElement.scrollTop || document.body.scrollTop; res.push(['scrollTop', sctop]); var item = document.getElementById('kw'); var rc = item.getBoundingClientRect(); var href = ''; res.push(['item', rc.left, rc.top, rc.width, rc.height, href]); return res; })();",
                "sub-page"=>[
                    "duration"=>3,
                    "operation"=>"browse"
                ],
                "operation"=>"click"
            ]
        ];
        array_push($operations,$keyWordArr,$page1,$page1Click);
        $action = [
            "url"=> "https://www.baidu.com/?tn=67005728_2_oem_dg",
            "mode"=> "load",
            "duration"=> 90,
            "operations"=> $operations
        ];
        return $action;
    }

    public function checkTaskConfig($param=[]){
        $data = [
//            'original_quantity'=>'',            // 原数量
//            'already_use_quantity'=>'',         // 已用数量
            'whether_left'=>'',                 // 是否剩余,1:有剩余，2:没有剩余
        ];
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(2);
        if(isset($param['type']) && $param['type'] == 'kuaipai'){
            $arr_str = "45,46,47,48,49";
            $redis = new \Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->select(2);
            $time_yymmdd = date('Y-m-d 00:00:01',time());
            $time_hhiiss = date('H:i:s',time());
            $sql1 = "SELECT * FROM `fa_task_config` WHERE Count > 0 and Id in (".$arr_str.") and  TIME_TO_SEC(`DateStart`) <= TIME_TO_SEC('".$time_yymmdd."')  AND TIME_TO_SEC(`DateEnd`) > TIME_TO_SEC('".$time_yymmdd."')  AND `TimeStart` <= '".$time_hhiiss."'  AND `TimeEnd` > '".$time_hhiiss."';";
            $result = Db::query($sql1);
            foreach($result as $k1=>$v1){
                $actual_count_target = $redis->zScore('task_config_'.date('Y-m-d'),$v1['Id'])?$redis->zScore('task_config_'.date('Y-m-d'),$v1['Id']):0;
                if((int)$actual_count_target <= $v1['Count']){
                    $data['whether_left'] = 1;
                    return $data;
                }
            }
            $data['whether_left'] = 2;
            return $data;
        }
        $data['whether_left'] = 2;
        return $data;
    }

}
